import { ADD_TODO, UPDATE_TODO } from "./constants";
const initState = {
  list: [
    {
      todoName: "吃饭",
      isDone: false,
      id: 1,
    },
    {
      todoName: "睡觉",
      isDone: true,
      id: 2,
    },
    {
      todoName: "打豆豆",
      isDone: false,
      id: 3,
    },
  ],
};

export default function renducer(state = initState, action) {
  let newState;
  switch (action.type) {
    // 添加
    case ADD_TODO:
      const todoName = action.todoName;
      const todo = {
        todoName,
        isDone: false,
        id: Date.now(),
      };
      newState = [...state.list];
      newState.push(todo);
      return {
        ...state,
        list: newState,
      };

    // 修改
    case UPDATE_TODO:
      const id = action.id;

      newState = [...state.list];
      newState = state.list.map((Item) => {
        if (Item.isDone === id) {
          Item.isDone = !Item.isDone;
        }
        return { ...Item };
      });
    default:
      return state;
  }
}
